<template>
  <div class="EditPersonalInformation">
    <NavBar title="编辑个人资料" backgroundColor="#161622">
      <template #left>
        <div class="left" @click="handleClick">
          <Icon name="zuojiantou" size="18" color="#fff"></Icon>
        </div>
      </template>
    </NavBar>
    <!-- 上传头像区域 -->
    <div class="upload_avatar">
      <div class="avatar">
        <img class="avatar_img" :src="avatar" alt="头像">
        <input type="file" class="avatar_input" accept="image/*" @change="handleAvatarChange">
      </div>
      <div class="upload_text">点击更换头像</div>
    </div>
    <!-- 收集用户信息区域 昵称 签名 性别 年龄 地区 -->
    <div class="from">
      <div class="from_item">
        <div class="from_item_label">昵称:</div>
        <div class="from_item_input">
          <input type="text" placeholder="请输入昵称" v-model="userInfo.userNickname">
        </div>
      </div>
      <div class="from_item">
        <div class="from_item_label">签名:</div>
        <div class="from_item_input">
          <input type="text" placeholder="请输入签名" v-model="userInfo.userDesc">
        </div>
      </div>
      <div class="from_item">
        <div class="from_item_label">性别</div>
        <div class="from_item_input">
          <!-- userInfo.userGender -->
          <div class="from_item_input_item" :class="[
            { active: userInfo.userGender === '男' },
            { male: userInfo.userGender === '男' },
            { female: userInfo.userGender === '女' }
          ]" @click="userInfo.userGender = '男'">
            <Icon name="nanxing" size="16" color="#1E3A8A"></Icon>
            <div class="from_item_input_item_text">男性</div>
          </div>

          <div class="from_item_input_item" :class="[
            { active: userInfo.userGender === '女' },
            { female: userInfo.userGender === '女' },
            { male: userInfo.userGender === '男' }
          ]" @click="userInfo.userGender = '女'">
            <Icon name="women-line" size="16" color="#F986C1"></Icon>
            <div class="from_item_input_item_text">女性</div>
          </div>
        </div>
      </div>
      <div class="from_item">
        <div class="from_item_label">年龄</div>
        <div class="from_item_input">
          <input type="number" placeholder="请输入年龄" v-model="userInfo.userAge">
        </div>
      </div>
      <div class="from_item">
        <div class="from_item_label">地区</div>
        <div class="from_item_input">
          <input type="text" placeholder="请输入地区" v-model="userInfo.userAddress">
        </div>
      </div>
    </div>

  </div>
  <Teleport to="body">
    <ImageCropper v-if="cropperVisible" :image-src="cropperImageSrc" @confirm="handleCropConfirm"
      @cancel="cropperVisible = false" />
  </Teleport>
</template>

<script setup>
import { ref } from 'vue';
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import { editMyInfoAPI, uploadAvatarAPI } from '@/api/my'
import ImageCropper from '@/views/my/ImageCropper/index.vue'


import { useMyUserInfoStore } from '@/stores/MyuserInfo'
const myUserInfoStore = useMyUserInfoStore()
const userInfo = myUserInfoStore.userInfo
// 图片数据
const avatar = ref(userInfo?.userAvatar)
// 对数据进行备份
const EdituserInfo = ref({ ...userInfo })
console.log('userInfo', userInfo)
console.log('EdituserInfo.value', EdituserInfo.value)
// 对比函数
const isEqual = (obj1, obj2) => {
  if (obj1 === obj2) {
    return true
  }
  if (obj1 === null || obj2 === null) {
    return false
  }
  if (typeof obj1 !== 'object' || typeof obj2 !== 'object') {
    return false
  }
  const keys1 = Object.keys(obj1)
  const keys2 = Object.keys(obj2)
  if (keys1.length !== keys2.length) {
    return false
  }
  for (const key of keys1) {
    if (!isEqual(obj1[key], obj2[key])) {
      return false
    }
  }
  return true
}



// 上传头像事件
const cropperVisible = ref(false)
const cropperImageSrc = ref('')
const originalAvatar = ref(userInfo?.userAvatar) // 保存原始头像URL
const avatarChanged = ref(false) // 标记头像是否发生变化

const handleAvatarChange = (e) => {
  const file = e.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => {
      // 显示裁剪器
      cropperVisible.value = true
      cropperImageSrc.value = reader.result
    }
  }
}

const handleCropConfirm = (croppedImageUrl) => {
  avatar.value = croppedImageUrl
  avatarChanged.value = true // 标记头像已变化
  cropperVisible.value = false
}

// 引入弹窗组件
import { showDialog } from '@/utils/dialog'

import { useRouter } from 'vue-router'
const router = useRouter()

// 检查数据是否发生变化（不包括头像）
const hasDataChanged = () => {
  return (
    userInfo.userNickname !== EdituserInfo.value.userNickname ||
    userInfo.userDesc !== EdituserInfo.value.userDesc ||
    userInfo.userGender !== EdituserInfo.value.userGender ||
    userInfo.userAge !== EdituserInfo.value.userAge ||
    userInfo.userAddress !== EdituserInfo.value.userAddress
  )
}

const handleClick = () => {
  // 检查是否有任何变化（包括头像和其他数据）
  const dataChanged = hasDataChanged()
  const avatarChangedValue = avatarChanged.value || avatar.value !== originalAvatar.value

  if (!dataChanged && !avatarChangedValue) {
    // 没有任何变化，直接返回
    router.push({
      name: 'my',
    })
    return;
  } else {
    // 有变化，弹窗提示用户确认
    showDialog({
      title: '保存修改',
      content: '是否保存修改？',
      onConfirm: () => {
        console.log('用户点击了确定')
        // 执行保存逻辑
        saveChanges()
      },
      onCancel: () => {
        console.log('用户点击了取消')
        // 执行取消逻辑
        router.push({
          name: 'my',
        })
      }
    })
  }
}

// 保存所有更改
const saveChanges = async () => {
  try {
    // 准备用户信息数据
    const userInfoData = {
      userNickname: userInfo.userNickname,
      userDesc: userInfo.userDesc,
      userGender: userInfo.userGender,
      userAge: userInfo.userAge,
      userAddress: userInfo.userAddress,
    }

    // 如果头像发生变化，添加userAvatar字段并上传头像
    if (avatarChanged.value || avatar.value !== originalAvatar.value) {
      console.log('上传头像...')

      // 添加头像字段到用户信息，转换为特定格式
      userInfoData.userAvatar = `/assets/avatar/${userInfo.userId}.png`

      // 直接使用base64格式上传头像
      const avatarData = {
        fieldName: avatar.value // 直接使用base64字符串
      }

      // 上传头像
      const uploadRes = await uploadAvatarAPI(userInfo.userId, avatarData)
      if (uploadRes.code !== 200) {
        console.error('头像上传失败:', uploadRes)
        // 可以在这里添加错误提示
        return
      }

      console.log('头像上传成功')
    }

    // 总是发送用户信息更新请求
    console.log('更新用户信息...')

    const res = await editMyInfoAPI(userInfo.userId, userInfoData)

    if (res.code !== 200) {
      console.error('用户信息更新失败:', res)
      // 可以在这里添加错误提示
      return
    }

    console.log('用户信息更新成功')

    // 所有操作成功，返回上一页
    router.push({
      name: 'my',
    })

  } catch (error) {
    console.error("保存更改时出错:", error);
    // 可以在这里添加错误提示
  }
}
</script>

<style lang="scss" scoped>
.EditPersonalInformation {
  background-color: #211832;
  height: 100vh;

  .upload_avatar {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 20px;
    border-bottom: 1px solid #292825cc;
    -webkit-tap-highlight-color: transparent;


    .avatar {
      position: relative;
      width: 100px;
      height: 100px;
      border-radius: 50%;
      overflow: hidden;
      cursor: pointer;

      .avatar_img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .avatar_input {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        opacity: 0;
        cursor: pointer;
      }
    }

    .upload_text {
      margin-top: 10px;
      font-size: 12px;
      color: #879394;
      cursor: pointer;
      font-weight: bold;
    }
  }

  .from {
    margin-top: 20px;
    display: flex;
    flex-direction: column;
    gap: 30px;
    padding: 20px;
    border-radius: 10px;

    .from_item {
      display: flex;
      align-items: center;
      gap: 5px;

      .from_item_label {
        font-size: 14px;
        color: #fff;
        flex-shrink: 0;
        width: 60px;
      }

      .from_item_input {
        flex: 1;
        display: flex;
        gap: 16px;
        align-items: center;

        input {
          width: 100%;
          padding: 10px;
          color: #fff;
          background-color: transparent;
          border-bottom: 1px solid #292825cc;
        }

        .from_item_input_item {
          -webkit-tap-highlight-color: transparent;
          -webkit-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
          outline: none;
          touch-action: manipulation;

          width: 45px;
          height: 45px;
          padding: 8px;
          border-radius: 50%;
          color: #fff;
          background-color: #2a1d3c;
          display: flex;
          justify-content: center;
          align-items: center;
          flex-direction: column;
          cursor: pointer;
          transition: all 0.4s cubic-bezier(0.25, 0.46, 0.45, 0.94);

          &:hover {
            transform: scale(1.05);
            box-shadow: 0 0 10px rgba(255, 255, 255, 0.1);
          }

          .from_item_input_item_text {
            font-size: 10px;
            font-weight: bold;
            line-height: 1;
            color: #ccc;
            margin-top: 2px;
            transition: color 0.3s ease;
          }

          &.active {
            transform: scale(1.1);
            color: #fff;

            .from_item_input_item_text {
              color: #000;
            }

            &.male {
              background-color: #209ff5;
              animation: pulsingShadowBlue 2s infinite ease-out;
            }

            &.female {
              background-color: #ee4fb2;
              animation: pulsingShadowPink 2s infinite ease-out;
            }
          }
        }
      }
    }
  }
}

// 蓝色脉动阴影（男性）
@keyframes pulsingShadowBlue {
  0% {
    box-shadow:
      0 0 0 2px rgba(255, 255, 255, 0.2),
      0 4px 12px rgba(32, 159, 245, 0.5),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }

  50% {
    box-shadow:
      0 0 0 8px rgba(255, 255, 255, 0),
      0 8px 24px rgba(32, 159, 245, 0.6),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }

  100% {
    box-shadow:
      0 0 0 12px rgba(255, 255, 255, 0),
      0 12px 32px rgba(32, 159, 245, 0.4),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }
}

// 粉色脉动阴影（女性）
@keyframes pulsingShadowPink {
  0% {
    box-shadow:
      0 0 0 2px rgba(255, 255, 255, 0.2),
      0 4px 12px rgba(238, 79, 178, 0.5),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }

  50% {
    box-shadow:
      0 0 0 8px rgba(255, 255, 255, 0),
      0 8px 24px rgba(238, 79, 178, 0.6),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }

  100% {
    box-shadow:
      0 0 0 12px rgba(255, 255, 255, 0),
      0 12px 32px rgba(238, 79, 178, 0.4),
      inset 0 0 0 2px rgba(255, 255, 255, 0.3);
  }
}
</style>